//
//  JEHCollectionViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/10.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHCollectionViewController.h"

#define kRowHeight 50

@interface JEHCollectionViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) JEHDataBaseHandle *handle;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataSource;

@end

@implementation JEHCollectionViewController

- (void)dealloc {
    
    [_handle release];
    [_tableView release];
    [_dataSource release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view nightMode];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createTableView];
    [self createHeaderView];
    
#pragma mark - collectionReloadData
    NSNotificationCenter *centers = [NSNotificationCenter defaultCenter];
    [centers addObserver:self selector:@selector(receiveNotification:) name:@"collectionReloadData" object:nil];
}

- (void)receiveNotification:(NSNotification *)notification {
    
    [self createTableView];
    [self.tableView reloadData];
}

#pragma mark - createHeaderView
- (void)createHeaderView {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeaderHeight)];
    [self.view addSubview:headerView];
    [headerView nightMode];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeaderHeight + 19, headerView.width, 1)];
    topView.backgroundColor = [UIColor grayColor];
    topView.alpha = 0.3;
    [headerView addSubview:topView];
    
    UIButton *backBotton = [UIButton buttonWithType:UIButtonTypeCustom];
    backBotton.frame = CGRectMake(0, 20, 50, kHeaderHeight);
    [backBotton setImage:[UIImage imageNamed:@"goBackButton"] forState:UIControlStateNormal];
    [backBotton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:backBotton];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width / 2 - 20, 20, 40, kHeaderHeight)];
    title.text = @"收藏";
    [headerView addSubview:title];
    [title nightMode];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(self.view.width - 40, 20, 30, kHeaderHeight);
    [rightButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:rightButton];
}

#pragma mark - goBackButton
- (void)backButtonAction:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - editButtonAction
- (void)editButtonAction:(UIButton *)sender {

    if (_dataSource) {
        
        for (int i = 0; i < self.dataSource.count; i++) {
            
            UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
            delete.frame = CGRectMake(self.view.width - kRowHeight / 2 - 10, i * kRowHeight + 20 + kHeaderHeight + kRowHeight / 4, kRowHeight / 2, kRowHeight / 2);
            delete.tag = 100 + i;
            [delete setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            [delete addTarget:self action:@selector(deleteCollectionAtRow:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:delete];
        }
    }
}

#pragma mark - deleteCollectionAtRow
- (void)deleteCollectionAtRow:(UIButton *)sender {
    
    JEHRootModel *rootModel = self.dataSource[sender.tag - 100];
    [self.handle openDataBase];
    [self.handle deleteFromDataBase:rootModel.title];
    [self.handle closeDataBase];
    
    UIButton *lastButton = (UIButton *)[self.view viewWithTag:100 + self.dataSource.count - 1];
    [lastButton removeFromSuperview];
    [self.dataSource removeObjectAtIndex:sender.tag - 100];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消收藏" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [alert dismissWithClickedButtonIndex:0 animated:NO];
    });
    [alert release];
    [self.tableView reloadData];
}

#pragma mark - createTableView
- (void)createTableView {
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    self.handle = [JEHDataBaseHandle shareDataBaseHandle];
    [self.handle openDataBase];
    self.dataSource = [NSMutableArray arrayWithArray:[self.handle selectAllFromDataBase]];
    [self.handle closeDataBase];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, self.view.width, self.view.height - 50) style:UITableViewStyleGrouped];
    [_tableView release];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView nightMode];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.view addSubview:_tableView];
    
    if (_dataSource.count == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有更多收藏" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alert dismissWithClickedButtonIndex:0 animated:NO];
        });
        [alert release];
    }
}

#pragma mark - UITableViewDelegateMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_dataSource) {
        
        return self.dataSource.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    JEHRootModel *rootModel = self.dataSource[indexPath.row];
    cell.textLabel.text = rootModel.title;
    [cell nightMode];
    [cell.textLabel nightMode];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    JEHRootModel *rootModel = self.dataSource[indexPath.row];
    JEHWebViewViewController *webView = [[JEHWebViewViewController alloc] init];
    webView.rootModel = rootModel;
    [self presentViewController:webView animated:YES completion:^{
        
    }];
    [webView release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
